<?php


namespace App\Http\Middleware;

use App\Models\Admin\Permissions;
use App\Models\Admin\Admin;
use \Illuminate\Support\Facades\Request;
use Closure;
use Illuminate\Support\Facades\Session;


/**
 * 检查用户是否存在操作权限
 * Class Auth
 * @package App\Http\Middleware
 */
class Auth
{
    public function handle($request, Closure $next)
    {
       $adminUserId         = Session::get('user_id');
       $route               = $this->getAccessMethods();
       $users               = new Admin();
       $permissions         = new Permissions();
       if(!in_array(1,Session::get('role_id'))){
           $userHasPermissions  = $users->find($adminUserId)->havePermissions->toArray();
           $permissions         = $permissions->getPermissions(array_column($userHasPermissions,'permission_id'));
            if(!in_array($route,$permissions->toArray())){
                if(Request::ajax()){
                    exit(json_encode(['code'=>10001,'message'=>'没有权限访问']));
                }
                return redirect('/admin/error');
            }
       }
        return $next($request);
    }

    /**
     * 获取模块 控制器 方法
     * @return mixed
     * @author: zhangfayuan
     * @date: 2019/7/12 16:32
     */
    final protected function getAccessMethods()
    {
        list($class, $method) = explode('@', request()->route()->getActionName());
        # 模块名
        $actions['module'] = str_replace(
            '\\',
            '.',
            str_replace(
                'App\\Http\\Controllers\\',
                '',
                trim(
                    implode('\\', array_slice(explode('\\', $class), 0, -1)),
                    '\\'
                )
            )
        );
        # 控制器名称
        $actions['controller'] = substr(strrchr($class, '\\'), 1);
//        str_replace(
//            'Controller',
//            '',
//            substr(strrchr($class, '\\'), 1)
//        );
        # 方法名
        $actions['action'] = $method;

        return $actions;
    }

}
